'''
Created on Jul 17, 2011

@author: mike
'''
from PyQt4 import QtGui, QtCore
from PyQt4.Qt import pyqtSignal as Signal 
from PyQt4.Qt import pyqtSlot as Slot 

from View.Widgets.EntityEditor.ComponentWidget import ComponentWidget
from View.Widgets.EntityEditor.ComponentEditor import ComponentEditor
import functools
import math
from Model.EditorPath import EditorPath
from View.Widgets.EntityEditor.AddEntity import AddEntity
from View.Widgets.EntityEditor import EntityDescr, TransformationComponentEditor
import View.Widgets.EntityEditor.TransformationComponentEditor

class EntityWidget(QtGui.QWidget):
    
    COMPONENT_HEIGHT = 50
    ENTITY_IMAGE_SIZE = 64
    
    def __init__(self, QScrollArea, QDockWidget, parent=None): 
       
        QtGui.QWidget.__init__ (self) 
        
        self.mDesWidget = None
        self.mAddWidget = None

        self.mScrollArea = QScrollArea
        self.mDockWidget = QDockWidget
        self.setWindowFlags( QtCore.Qt.Window )
        self.resize(250, 150)
        self.setWindowTitle('simple')
     
        self.timer = QtCore.QTimer(self)
        self.mCoponentEditor = None
        self.mComponentWidget = None
        
        self.timer.start(1000)
        self.mComponentList = []
        self.setupLayout()
        
        #self.addComponent("Label")
        #self.addComponent("Label")
        #self.addComponent("Label")
        self.mScrollArea = QScrollArea
        self.mEntity = None
        
        self.mNoEntityImage = QtGui.QImage()
        self.mNoEntityImage.load(EditorPath.mImageFolderPath + EditorPath.mNoEntityImageFile)
        
        #Font
        self.mTextPen       = QtGui.QPen(QtCore.Qt.white, 3, QtCore.Qt.SolidLine);
        self.mFont          = QtGui.QFont()
        self.mFont.setPixelSize(20)
        self.mFont.setBold(1)
        


  
        
    def setupLayout(self):
        self.mVerticalLayoutWidget = QtGui.QWidget(self)
        self.mVerticalLayout = QtGui.QVBoxLayout(self.mVerticalLayoutWidget)
        self.mVerticalLayout.setMargin(0)
        self.mVerticalLayout.setSpacing(0)
        
        self.updateLayoutGeometry()
        
            
    def updateLayoutGeometry(self):
        editMinH = 0
        if self.mCoponentEditor:
            editMinH =  self.mComponentEditorHeight # self.mCoponentEditor.height()
            print("Component height" + str(editMinH))
            
        contentSize = QtGui.QDockWidget.contentsRect(self.mDockWidget)
        
        componentsTotalHeight = self.COMPONENT_HEIGHT * len(self.mComponentList) + editMinH
        enitityWidgetHeight = contentSize.height() - 31
        heightToSet = 0
        if componentsTotalHeight > enitityWidgetHeight:
            heightToSet = componentsTotalHeight
        else:
            heightToSet = enitityWidgetHeight
        
            
        #dockContentHeight = self.mDockWidget.height() - self.mDockWidget.titleBarWidget().height()
        self.resize(contentSize.width() - 5, heightToSet)
        
        self.mVerticalLayoutWidget.setGeometry(
                                               QtCore.QRect(0, 
                                                            0, 
                                                            self.width(), 
                                                            componentsTotalHeight))
        
        
    def addComponent(self, label):
        
        self.component = None
        
        self.component = ComponentWidget("Component", self)
        
        #self.components.append(self.component)
        #s = Signal()
        #s = self.component.speakNumber
        # s.
        
        self.component.speakNumber.connect(self.saySomething)
        
        
        self.component.speakWord.connect(self.saySomething)
        self.component.popComponentEditor.connect(self.popComponent)
        self.component.repaintEditor.connect(self.repaintEditor)
        self.mVerticalLayout.addWidget(self.component)
        
        self.mComponentList.append(self.component)
        
        self.updateLayoutGeometry()
        
    def setupComponent(self, component, idx=-1):
        component.popComponentEditor.connect(self.popComponent)
        component.repaintEditor.connect(self.repaintEditor)
        if idx == -1:
            self.mVerticalLayout.addWidget(component)
        else:
            self.mVerticalLayout.insertWidget(idx, component)
        self.mComponentList.append(component)
        self.updateLayoutGeometry()
        
        
    def paintEvent(self, QPaintEvent):
        self.updateLayoutGeometry()
        
        painter =  QtGui.QPainter(self);
        painter.setRenderHint(QtGui.QPainter.Antialiasing)
        
        if not self.mEntity:
            self.drawNoEntity(painter)
        
    def setEntity(self, entity=None):
        
        if self.mDesWidget:
            self.mVerticalLayout.removeWidget(self.mDesWidget)
            self.mVerticalLayout.removeWidget(self.mAddWidget)
            self.mDesWidget.hide()
            self.mAddWidget.hide()

        if self.mCoponentEditor:
            self.mVerticalLayout.removeWidget(self.mCoponentEditor)
            self.mCoponentEditor.hide()
            self.mCoponentEditor = None
        
        for component in self.mComponentList:
            self.mVerticalLayout.removeWidget(component)
            #if component.mIsOpen:
                #self.mVerticalLayout.removeWidget(component.mCoponentEditor)
            #    component.mCoponentEditor.hide()
            component.hide()
            
        self.mDesWidget = None
        self.mAddWidget = None

        
        
        self.mEntity = entity
        self.mComponentList = []
        
        # Add description
        if self.mEntity:
            cWid = ComponentWidget("", None)
            entDescr = EntityDescr.EntityDescr("", None)
            cWid.setComponentEditor(entDescr)
            entDescr.setEntityName("Entity2")
            entDescr.setEntityGuid("Folder1/Entity2")
            self.setupComponent(cWid)
            self.mDesWidget = cWid
        
        # Add coponents
        for component in self.mEntity.mComponentList:
            if component.mType == "Material":
                '''
                '''
            elif component.mType == "Mesh":
                '''
                '''
            elif component.mType == "Transformation":
                '''
                '''
                cWid = ComponentWidget("", None)
                compEditor = TransformationComponentEditor.TranformationComponentEditor("", None)
                cWid.setComponentEditor(compEditor)
                self.setupComponent(cWid, 1)
                
        # Add add entity
        if self.mEntity:
            add = AddEntity(self, "", self)
            self.setupComponent(add)
            self.mAddWidget = add
            #self.mComponentList.append(add)
            
    def addTransformation(self):
        cWid = ComponentWidget("", None)
        compEditor = TransformationComponentEditor.TranformationComponentEditor("", None)
        cWid.setComponentEditor(compEditor)
        self.setupComponent(cWid, 1)
            
    
    def drawNoEntity(self, QPainter):
        ##################
        # Draw image
        ##################
        centerX = self.width() / 2
        centerY = self.height() / 2
        leftX = centerX - self.ENTITY_IMAGE_SIZE / 2
        topY = centerY - self.ENTITY_IMAGE_SIZE / 2
        
        target = QtCore.QRectF( leftX, 
                         topY, 
                         self.ENTITY_IMAGE_SIZE, self.ENTITY_IMAGE_SIZE) 
        
        source = QtCore.QRectF(0, 
                        0, 
                        self.mNoEntityImage.width(), 
                        self.mNoEntityImage.height()) 
        QPainter.drawImage(target, self.mNoEntityImage, source)
        ##################
        # Draw Text
        ##################
        text = "Empty"
        QPainter.setFont(self.mFont)
        QPainter.setPen(self.mTextPen)
        metrics = QPainter.fontMetrics()
        fontBox = metrics.boundingRect(text)
        
        textRec = QtCore.QRectF(self.width() / 2 - (fontBox.width() / 2), 
                         self.height() / 2 - fontBox.height() / 2 + self.ENTITY_IMAGE_SIZE/2, 
                         self.width() / 2 + fontBox.width() / 2,
                         self.height() / 2 + fontBox.height() / 2 + self.ENTITY_IMAGE_SIZE/2)  
        
        QPainter.drawText(textRec, QtCore.Qt.AlignLeft, text);
        
    @Slot(int)
    @Slot(str)
    def saySomething(self, stuff):
        print (stuff)
    
    @Slot(int, QtGui.QWidget)
    def popComponent(self, componentEditor, componentWidget):
        if self.mComponentWidget:
            self.mComponentWidget.setIsOpen(0)
        if self.mCoponentEditor == componentEditor:
            self.mVerticalLayout.removeWidget(self.mCoponentEditor)
            self.mCoponentEditor.hide()
            self.mCoponentEditor = None
            self.mComponentWidget = None
            self.updateLayoutGeometry()
            return
        
        if self.mCoponentEditor:
            self.mCoponentEditor.hide()
            self.mVerticalLayout.removeWidget(self.mCoponentEditor)
            

        self.mComponentWidget = componentWidget
        self.mCoponentEditor = componentEditor
        if self.mCoponentEditor:
            self.mComponentEditorHeight = self.mCoponentEditor.height()
            self.mComponentWidget.setIsOpen(1)
            idxOfWid = self.mVerticalLayout.indexOf(self.mComponentWidget) + 1
            self.mVerticalLayout.insertWidget(idxOfWid, self.mCoponentEditor)
            self.mCoponentEditor.show()
            
        self.updateLayoutGeometry()
        
        #self.connect(self.timer, QtCore.SIGNAL("timeout()"), functools.partial( self.componentEditor.repaintEditor, self))
        #self.connect(self.timer, QtCore.SIGNAL("mouseMoveEvent()"), self.update)
        
        #self.mCoponentEditor.show()
        
        
        
        
    
    
    def repaintEditor(self):
        print("repaintEditor")
        
        self.updateLayoutGeometry()
        if self.mComponentWidget:
            self.mComponentWidget.updateComponentEditorPoition()
        #widjet = componentWidget
        #globalPos = self.component.mapToGlobal(self.component.rect().topRight())
        #self.componentEditor.move(globalPos.x(),globalPos.y())
        #self.componentEditor.move(globalPos)
        self.update()
    


if __name__ == '__main__':
    
    import sys
    app = QtGui.QApplication(sys.argv)
    theTool = EntityWidget()
    theTool.show()
    app.exec_()
